package com.qkl.common.publics.web.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.qkl.common.publics.utils.CommonCryptoUtils;
import com.qkl.common.publics.utils.ErrorCodeUtils;
import com.qkl.common.publics.utils.Result;
import com.qkl.common.publics.utils.PublicSessionUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public  class AppInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Value("${server.servlet.context-path}")
    private String serverContextPath;

    @Value("${public.baseURL}")
    private String publicBaseURL;

    private String getAccessTokenURL;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        String sign = StringUtils.trimToEmpty(request.getHeader("sign"));
        String appId = StringUtils.trimToEmpty(request.getParameter("appId"));
        log.info("===preHandle.appId={},uri={},sign={}",appId,uri,sign);

        Result result = null;
        if(StringUtils.isEmpty(sign)){
            if(StringUtils.isEmpty(this.getAccessTokenURL)){
                this.getAccessTokenURL = serverContextPath + publicBaseURL + "/getAccessToken";
            }
            log.info("===preHandle.getAccessTokenURL={}",this.getAccessTokenURL);
            if(uri.startsWith(this.getAccessTokenURL)){
                CommonCryptoUtils.PublicCrypto crypto = new CommonCryptoUtils.PublicCrypto();
                crypto.setTimestamp(System.currentTimeMillis());
                crypto.setAppId(appId);
                if(StringUtils.isEmpty(appId)){
                    crypto.setAppId(CommonCryptoUtils.PUBLIC_APP_ID);
                }
                PublicSessionUtils.setPublicCrypto(crypto);
            }else {
                result = Result.error(ErrorCodeUtils.SIGN_EMPTY, ErrorCodeUtils.SIGN_EMPTY_MSG);
            }
        }else {
            CommonCryptoUtils.PublicCrypto crypto = CommonCryptoUtils.decryptPublic(sign);
            if(null == crypto ){
                result = Result.error(ErrorCodeUtils.SIGN_INVALID,ErrorCodeUtils.SIGN_INVALID_MSG);
            }else if(crypto.timeout()){
                result = Result.error(ErrorCodeUtils.SIGN_EXPIRE,ErrorCodeUtils.SIGN_EXPIRE_MSG);
            }else {
                PublicSessionUtils.setPublicCrypto(crypto);
            }
        }

        if(null != result){
            response.reset();
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().print(objectMapper.writeValueAsString(result));
            response.getWriter().close();
            return false;
        }

        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }


}
